<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="dirName"
              placeholder="请输入分类名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              :data="dirOptions"
              :props="{ label: 'fileName', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="文件名" prop="fileName">
            <el-input
                v-model="queryParams.fileName"
                placeholder="请输入文件名"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="分类" prop="fileCategory">
            <el-input
                v-model="queryParams.fileCategory"
                placeholder="请输入分类"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="标签" prop="fileTags">
            <el-input
                v-model="queryParams.fileTags"
                placeholder="请输入标签"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['sources:file:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['sources:file:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['sources:file:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleExport"
                v-hasPermi="['sources:file:export']"
            >导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="分类" align="center" prop="fileCategory">
            <template #default="scope">
              <span>
                <svg-icon style="width: 20px; height: 20px;" v-if="scope.row.fileCategory === 0" icon-class="folderOpen" />
                <svg-icon style="width: 20px; height: 20px;" v-else icon-class="fileText" />
              </span>
            </template>
          </el-table-column>
          <el-table-column label="目录" align="center" prop="pid"/>
          <el-table-column label="文件名" align="center" width="240px" show-overflow-tooltip prop="fileName" />
          <el-table-column label="文件类型" align="center" prop="fileType"/>
          <el-table-column label="文件大小" align="center" prop="fileSize">
            <template #default="scope">
              {{ convertFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="fileSort"/>
          <el-table-column label="标签" align="center" prop="fileTags"/>
          <el-table-column label="操作" align="center" fixed="right" width="200px" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                  type="text"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['sources:file:edit']"
              >修改
              </el-button>
              <el-button
                  type="text"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['sources:file:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改文件管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="fileRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="目录" prop="pid">
          <el-tree-select
              v-model="form.pid"
              :data="dirOptions"
              :props="{label: 'fileName', children: 'children'}"
              value-key="id"
              placeholder="请选择目录"
              check-strictly
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名"/>
        </el-form-item>
        <el-form-item label="是否文件" prop="fileCategory">
          <el-switch v-model="form.fileCategory" :active-value="1" :inactive-value="0"/>
        </el-form-item>
        <el-form-item v-if="form.fileCategory === 1" label="上传文件" prop="filePath">
          <file-upload v-model="form.filePath" @change="handleFileChange" :limit="1" auth="Y"/>
        </el-form-item>
        <el-form-item v-if="form.fileCategory === 1" label="文件大小" prop="fileSize">
          <el-input v-model="form.fileSize" readonly placeholder="请输入文件大小"/>
        </el-form-item>
        <el-form-item label="排序" prop="fileSort">
          <el-input v-model="form.fileSort" placeholder="请输入排序"/>
        </el-form-item>
        <el-form-item label="标签" prop="fileTags">
          <el-input v-model="form.fileTags" placeholder="请输入标签"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="File">
import {addFile, delFile, getFile, listFile, updateFile, listFileAll} from "@/api/sources/file";

const {proxy} = getCurrentInstance();

const fileList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pid: null,
    pids: null,
    fileName: null,
    fileCategory: null,
    filePath: null,
    fileType: null,
    fileSize: null,
    fileSort: null,
    fileTags: null,
    deptId: null,
    tenantId: null,
  },
  rules: {}
});

// 分类名称
const dirName = ref('');
const dirOptions = ref([]);

const {queryParams, form, rules} = toRefs(data);

/** 查询文件管理列表 */
function getList() {
  loading.value = true;
  listFile(queryParams.value).then(response => {
    fileList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    pid: null,
    pids: null,
    fileName: null,
    fileCategory: null,
    filePath: null,
    fileType: null,
    fileSize: null,
    fileSort: null,
    fileTags: null,
    deptId: null,
    tenantId: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    delFlag: null
  };
  proxy.resetForm("fileRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
  getTreeList();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  if (queryParams.value.pid) {
    form.value.pid = queryParams.value.pid;
  }
  open.value = true;
  title.value = "添加文件管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getFile(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改文件管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["fileRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFile(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFile(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除文件管理编号为"' + _ids + '"的数据项？').then(function () {
    return delFile(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sources/file/export', {
    ...queryParams.value
  }, `file_${new Date().getTime()}.xlsx`)
}

function getTreeList() {
  listFileAll({ fileCategory: 0 }).then(res => {
    if (res.code === 200) {
      // 初始化数结构数据
      const menu = { id: '0', fileName: "根目录", children: [] };
      menu.children = proxy.handleTree(res.data, "id", "pid");
      dirOptions.value = [menu];
    }
  });
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.pid = data.id;
  handleQuery();
};

// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}

function handleFileChange(files) {
  if (files && files[0]) {
    const file = files[0];
    if (file.rows) {
      form.value.fileName = getFileName(file.rows.fileName);
      form.value.fileSize = file.rows.fileSize;
    }
  }
}

getList();
getTreeList();
</script>
